'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Save, Eye, Loader2, AlertCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { knowledgeAPI, categoriesAPI, tagsAPI } from '@/lib/api'
import { toast } from 'sonner'
import { KnowledgeBase, KnowledgeBaseUpdateData, Category, Tag } from '@/lib/types'
import { 
  CompactLayout, 
  CompactHeading, 
  CompactSubheading,
  CompactCard 
} from '@/components/ui/compact-layout'

export default function KnowledgeEditPage() {
  const router = useRouter()
  const params = useParams()
  const articleId = params.id as string
  
  const [article, setArticle] = useState<KnowledgeBase | null>(null)
  const [categories, setCategories] = useState<Category[]>([])
  const [tags, setTags] = useState<Tag[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  // 表单数据
  const [formData, setFormData] = useState<KnowledgeBaseUpdateData>({
    title: '',
    description: '',
    content: '',
    categoryId: '',
    tagIds: [],
    status: 'DRAFT',
    featured: false
  })

  // 获取文章详情
  const fetchArticle = async () => {
    try {
      setIsLoading(true)
      const response = await knowledgeAPI.getKnowledgeBase(articleId)
      setArticle(response)
      
      // 设置表单数据
      setFormData({
        title: response.title,
        description: response.description || '',
        content: response.content,
        categoryId: response.category?.id || '',
        tagIds: response.tags?.map(tag => tag.id) || [],
        status: response.status,
        featured: response.featured
      })
    } catch (error: any) {
      console.error('Failed to fetch article:', error)
      toast.error(error.message || '获取文章详情失败')
      router.push('/knowledge')
    } finally {
      setIsLoading(false)
    }
  }

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await categoriesAPI.getCategories()
      setCategories(response || [])
    } catch (error) {
      console.error('Failed to fetch categories:', error)
    }
  }

  // 获取标签列表
  const fetchTags = async () => {
    try {
      const response = await tagsAPI.getAllTags()
      setTags(response || [])
    } catch (error) {
      console.error('Failed to fetch tags:', error)
    }
  }

  // 处理表单输入变化
  const handleInputChange = (field: keyof KnowledgeBaseUpdateData, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 处理标签选择
  const handleTagToggle = (tagId: string) => {
    setFormData(prev => ({
      ...prev,
      tagIds: prev.tagIds?.includes(tagId)
        ? prev.tagIds.filter(id => id !== tagId)
        : [...(prev.tagIds || []), tagId]
    }))
  }

  // 保存文章
  const handleSave = async () => {
    if (!formData.title.trim()) {
      toast.error('请输入文章标题')
      return
    }

    if (!formData.content.trim()) {
      toast.error('请输入文章内容')
      return
    }

    try {
      setIsSubmitting(true)
      await knowledgeAPI.updateKnowledgeBase(articleId, formData)
      toast.success('文章保存成功')
      router.push(`/knowledge/${articleId}`)
    } catch (error: any) {
      console.error('Failed to save article:', error)
      toast.error(error.message || '保存文章失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 预览文章
  const handlePreview = () => {
    // 在新窗口打开预览
    const previewWindow = window.open(`/knowledge/${articleId}`, '_blank')
    if (previewWindow) {
      previewWindow.focus()
    }
  }

  // 初始化加载
  useEffect(() => {
    if (articleId) {
      fetchArticle()
      fetchCategories()
      fetchTags()
    }
  }, [articleId])

  if (isLoading) {
    return (
      <CompactLayout>
        <div className="flex items-center justify-center h-64">
          <div className="flex items-center space-x-2">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
            <span>加载中...</span>
          </div>
        </div>
      </CompactLayout>
    )
  }

  if (!article) {
    return (
      <CompactLayout>
        <div className="text-center py-8">
          <p className="text-muted-foreground">文章不存在或已被删除</p>
          <Button onClick={() => router.push('/knowledge')} className="mt-4">
            返回文章列表
          </Button>
        </div>
      </CompactLayout>
    )
  }

  return (
    <CompactLayout>
      {/* 页面头部 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.push(`/knowledge/${articleId}`)}
            className="h-8 w-8"
          >
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <CompactHeading>编辑文章</CompactHeading>
            <CompactSubheading>
              编辑文章: {article.title}
            </CompactSubheading>
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <Button
            variant="outline"
            onClick={handlePreview}
            className="flex items-center space-x-2"
          >
            <Eye className="h-4 w-4" />
            <span>预览</span>
          </Button>
          <Button
            onClick={handleSave}
            disabled={isSubmitting}
            className="flex items-center space-x-2"
          >
            {isSubmitting ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            <span>{isSubmitting ? '保存中...' : '保存'}</span>
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* 主要内容编辑 */}
        <div className="lg:col-span-3 space-y-6">
          {/* 基本信息 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">基本信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="title">文章标题 *</Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => handleInputChange('title', e.target.value)}
                  placeholder="请输入文章标题"
                  className="w-full"
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="description">文章描述</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="请输入文章描述（可选）"
                  rows={3}
                  className="w-full"
                />
              </div>
            </CardContent>
          </CompactCard>

          {/* 文章内容 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">文章内容 *</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <Label htmlFor="content">内容</Label>
                <Textarea
                  id="content"
                  value={formData.content}
                  onChange={(e) => handleInputChange('content', e.target.value)}
                  placeholder="请输入文章内容"
                  rows={20}
                  className="w-full font-mono text-sm"
                />
                <p className="text-xs text-muted-foreground">
                  支持 Markdown 格式，也可以直接输入 HTML 内容
                </p>
              </div>
            </CardContent>
          </CompactCard>
        </div>

        {/* 侧边栏设置 */}
        <div className="space-y-6">
          {/* 发布设置 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">发布设置</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="status">发布状态</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value) => handleInputChange('status', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="DRAFT">草稿</SelectItem>
                    <SelectItem value="PUBLISHED">发布</SelectItem>
                    <SelectItem value="ARCHIVED">归档</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div className="flex items-center justify-between">
                <Label htmlFor="featured">设为精选</Label>
                <Switch
                  id="featured"
                  checked={formData.featured}
                  onCheckedChange={(checked) => handleInputChange('featured', checked)}
                />
              </div>
            </CardContent>
          </CompactCard>

          {/* 分类设置 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">分类设置</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="category">选择分类</Label>
                <Select
                  value={formData.categoryId || "none"}
                  onValueChange={(value) => handleInputChange('categoryId', value === "none" ? "" : value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择分类" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">无分类</SelectItem>
                    {categories.map((category) => (
                      <SelectItem key={category.id} value={category.id}>
                        {category.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </CompactCard>

          {/* 标签设置 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">标签设置</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>选择标签</Label>
                <div className="flex flex-wrap gap-2">
                  {tags.map((tag) => (
                    <Badge
                      key={tag.id}
                      variant={formData.tagIds?.includes(tag.id) ? "default" : "outline"}
                      className="cursor-pointer hover:opacity-80"
                      onClick={() => handleTagToggle(tag.id)}
                    >
                      {tag.name}
                    </Badge>
                  ))}
                </div>
                {tags.length === 0 && (
                  <p className="text-xs text-muted-foreground">
                    暂无可用标签
                  </p>
                )}
              </div>
            </CardContent>
          </CompactCard>

          {/* 保存提示 */}
          <CompactCard>
            <CardContent className="pt-6">
              <div className="flex items-start space-x-2 text-sm text-muted-foreground">
                <AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
                <div>
                  <p className="font-medium mb-1">保存提示</p>
                  <ul className="space-y-1 text-xs">
                    <li>• 标题和内容为必填项</li>
                    <li>• 草稿状态的文章不会对外显示</li>
                    <li>• 精选文章会在首页突出显示</li>
                    <li>• 修改后记得点击保存按钮</li>
                  </ul>
                </div>
              </div>
            </CardContent>
          </CompactCard>
        </div>
      </div>
    </CompactLayout>
  )
}
